<?php

namespace App\Repositories\Manage;

use App\Models\Category;
use App\Models\Content;

class ArticleRepository
{

    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = Content::query()
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("title", "like", "%{$filter['keywords']}%");
            })
            ->where(['is_deleted' => 2])
            ->orderBy("id", "desc")
            ->paginate($pageSize, "*", null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);
        foreach ($res['items'] as $k => &$v) {
            if ($v['category_id']) {
                $v['category_title'] = Category::query()->where(['status' => 1, 'id' => $v['category_id']])->value("title");
            }
        }

        return $res;
    }

    public function getOne($id = null)
    {
        return Content::query()->where("id", $id)->first();
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);

        if (intval($id)) {
            Content::where("id", $id)->update($data);
            return $id;
        } else {
            return Content::create($data)->id;
        }
    }

    /**
     * 删除
     * @param null $id
     */
    public function deleteArticle($id = null)
    {
        if (!intval($id))
            return retFail("参数错误");

        Content::where(['id' => intval($id)])->delete();

        return retSuc([], "删除成功");
    }

}
